package Demo;

import java.io.File;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要查找的目录: ");
        String path = scanner.nextLine();
        System.out.println("请输入要查找的文件名: ");
        String fileName = scanner.nextLine();

        File dir = new File(path);

        if (!(dir.exists() || dir.isDirectory())) {
            System.out.println("目录不存在");
            return;
        }
        scanDir(dir, fileName);

    }

    private static void scanDir(File dir, String fileName) {
        File[] files = dir.listFiles();
        if (files == null) {
            return;
        }
        for (File file : files) {
            if (file.isFile() && file.getName().contains(fileName)) {
                tryDelete(file);
            } else if (file.isDirectory()) {
                scanDir(file, fileName);
            } else {
                continue;
            }
    }
}

    private static void tryDelete(File file) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("是否删除文件: " + file.getName() + " (Y/N)");
        String input = scanner.nextLine();
        if (input.equalsIgnoreCase("Y")) {
            if (file.delete()) {
                System.out.println("文件删除成功");
            } else {
                System.out.println("文件删除失败");
            }
        }
    }
}
